package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserRoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    UserRoleDao userRoleDao;
    @Override
    @Transactional
    public void add(SysUser sysUser, Integer[] checkitemIds) {
//添加用户信息到数据库
        userRoleDao.add(sysUser);
        //维护用户和角色的关系
        if(sysUser.getId()!=null&& checkitemIds !=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                userRoleDao.addRelation(sysUser.getId(),checkitemId);
            }
        }
    }



    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<SysUser> page = userRoleDao.findByUsername(queryPageBean.getQueryString());
        log.debug("page{"+page+"}");
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void delById(Integer id) {
        userRoleDao.delRoleRelation(id);
        userRoleDao.delById(id);
    }

    @Override
    public SysUser findById(Integer id) {
        return userRoleDao.findById(id);
    }

    @Override
    public List<Integer> findRoleById(Integer id) {
        return userRoleDao.findRoleById(id);
    }

    @Override
    public void edit(SysUser sysUser, Integer[] checkitemIds) {
        userRoleDao.edit(sysUser);
        userRoleDao.delRoleRelation(sysUser.getId());
        //维护新的关系
        if(sysUser.getId()!=null&& checkitemIds !=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                userRoleDao.addRelation(sysUser.getId(),checkitemId);
            }
        }
    }


}
